package com.rockcent.api.controller;

import com.rockcent.api.Routes;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.helper.CategoryHelper;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.ProductClientType;
import com.rockcent.mall.lib.domain.enumclass.ProductEventType;
import com.rockcent.mall.lib.domain.enumclass.ProductSourceType;
import com.rockcent.mall.lib.domain.enumclass.ProductType;
import com.rockcent.mall.lib.dto.ProductDto;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.helper.BaseUserHelper;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.ProductSrv;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by marco on 2017/7/14.
 */
@RestController
@RequestMapping(value = Routes.API_VERSION)
public class MallProductCategoryController extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MallProductCategoryController.class);

    @Autowired
    private BaseUserHelper userHelper;

    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private CategoryHelper categoryHelper;

    @Autowired
    private ProductSrv productSrv;

    @Autowired
    private MerchantProductCategoriesRepository merchantProductCategoriesRepository;

    @Autowired
    private MerchantProductRepository merchantProductRepository;

    @Autowired
    private MerchantOrderItemRepository merchantOrderItemRepository;

    @Autowired
    private ProductEventRepository productEventRepository;

    /**
     * @api {get} /v1/mall/product/category/list 产品品类列表
     * @apiGroup MALL_PRODUCT
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiSuccess {Long} id 品类ID
     * @apiSuccess {String} name 品类名称
     * @apiSuccess {Long} mallId 平台ID
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     *      "code": "1",
     *      "desc": "成功"
     *      "data": [
     *           {
     *           "id": 1,
     *           "name": "童装",
     *           "mallId": 1
     *           },
     *       ]
     * }
     */
    @RequestMapping(value = Routes.MALL_PRODUCT_CATEGORY_LIST, method = RequestMethod.GET)
    public JsonResult categoryList(HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (userInfoDto.mall == null || userInfoDto.mall.getId() == null) {
                jsonResult.remind("平台id 不能为空", log);
                return;
            }
            List<Category> categoryList = categoryRepository.findByMallIdAndVisibleAndIsDeleteAndParentIdIsNull(userInfoDto.mall.getId(), true, Whether.NO);
            jsonResult.data = categoryList;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /v1/mall/product/list 产品列表分页
     * @apiGroup MALL_PRODUCT
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {String} keyword 产品编号/名称
     * @apiParam {String} merchantName 商家名称
     * @apiParam {String=SERVICE("服务"), GOODS("商品"), ALL("全部")} type <code>必须参数</code> 产品类型 默认 ALL
     * @apiParam {Integer=SELF("自营"), MARKET("分销"), ALL("全部")} productSourceType <code>必须参数</code>  产品来源 默认 ALL
     * @apiParam {String} categoryId 品类 默认全部传空
     *
     * @apiSuccess {Long} id 产品ID
     * @apiSuccess {String} type 产品类型
     * @apiSuccess {String} name 产品名称
     * @apiSuccess {BigDecimal} sellPrice 出售价
     * @apiSuccess {Long} quantity 库存量
     * @apiSuccess {String} logoUrl LOGO图
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {String} marketId 分销产品唯一的识别码
     * @apiSuccess {String} merchantName 商家名称
     * @apiSuccess {String} resellFee 分销佣金
     * @apiSuccess {Long} categoryId 品类ID
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功"
     * "data":{
     *      "id": 71,
     *      "type": "GOODS",
     *      "name": "宇宙",
     *      "sellPrice": 100,
     *      "quantity": 998,
     *      "logoUrl": "/20160601/201606011413084VOvLKgN.jpg",
     *      "mallId": 1,
     *      "merchantId": 1,
     *      "resellFee": 5,
     *      "marketId": 232,
     *      "categoryId": 232,
     *  },
     *  .....
     * }
     */
    @RequestMapping(value = Routes.MALL_PRODUCT_LIST, method = RequestMethod.GET)
    public JsonResult productList(HttpServletRequest request, ProductDto productDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (userInfoDto.mall == null || userInfoDto.mall.getId() == null) {
                jsonResult.remind("平台id 不能为空", log);
                return;
            }
            if (StringUtils.isEmpty(productDto.getProductSourceType()) || !EnumUtils.isValidEnum(ProductSourceType.class, productDto.getProductSourceType())) {
                jsonResult.remind("产品来源只允许 ALL(\"全部\"), SELF(\"自营\"), MARKET(\"分销\"", log);
                return;
            }
            if (StringUtils.isEmpty(productDto.getType()) || !EnumUtils.isValidEnum(ProductType.class, productDto.getType())) {
                jsonResult.remind("产品类型只允许 SERVICE(\"服务\"), GOODS(\"商品\"), ALL(\"全部\")", log);
                return;
            }
            //分类不为空
            List<Long> categoryIds = new ArrayList<>();
            if (productDto.getCategoryId() != null) {
                categoryIds = categoryHelper.categoryIds(userInfoDto.mall.getId(), Arrays.asList(productDto.getCategoryId()), null);
                if (categoryIds.size() == 0) {
                    categoryIds.add(productDto.getCategoryId());
                }
            }
            PageResult<ProductDto> pageResult = productSrv.findProducts(userInfoDto.mall.getId(), productDto.getType(), productDto.getProductSourceType(), productDto.getMerchantName(), productDto.getKeyword(), categoryIds, this.getPage(productDto.getPageNo(), productDto.getPageSize()));
            if (productDto.getCategoryId() != null) {
                pageResult.data.stream().map(product -> {
                    product.setCategoryId(productDto.getCategoryId());
                    return product;
                }).collect(Collectors.toList());
            } else {
                pageResult.data.stream().map(product -> {
                    Long productId = product.getId();
                    //分销产品
                    if (product.getMarketId() != null) {
                        productId = product.getMarketId();
                    }
                    List<ProductCategories> productCategories = merchantProductCategoriesRepository.findByProductId(productId);
                    if (productCategories.size() > 0) {
                        product.setCategoryId(productCategories.get(0).getCategoryId());
                        Category category = categoryRepository.findByIdAndMallId(productCategories.get(0).getCategoryId(), userInfoDto.mall.getId());
                        if (category != null) {
                            product.setCategoryId(category.getParentId());
                            Category parentCategory = categoryRepository.findByIdAndMallId(category.getParentId(), userInfoDto.mall.getId());
                            if (parentCategory != null) {
                                product.setCategoryId(parentCategory.getParentId());
                            }
                        }
                    }
                    return product;
                }).collect(Collectors.toList());
            }
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /v1/mall/product/save 保存精选产品
     * @apiGroup MALL_PRODUCT
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {List} ids <code>必要参数</code> 产品ID集合
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *      "success": "Y"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_PRODUCT_SAVE, method = RequestMethod.POST)
    public JsonResult save(@RequestBody ProductDto productDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (userInfoDto.mall == null || userInfoDto.mall.getId() == null) {
                jsonResult.remind("平台id 不能为空", log);
                return;
            }
            List<Long> ids = productDto.getIds();
            if (ids == null || ids.size()==0) {
                jsonResult.remind("产品id 不能为空", log);
                return;
            }
            List<Product> products = merchantProductRepository.findByIdInAndMallId(ids,userInfoDto.mall.getId());
            if(products==null) {
                jsonResult.remind("产品id 不存在", log);
                return;
            }
            if(ids.size()!=products.size()) {
                jsonResult.remind("产品数据有些已不存在", log);
                return;
            }
            productSrv.saveExplosionProduct(userInfoDto.mall.getId(),ids);
            String ret = "{\"success\":\"Y\"}";
            jsonResult.data = JSONObject.fromObject(ret);
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /v1/mall/explosion/product/list 精选产品列表
     * @apiGroup MALL_PRODUCT
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {Long} merchantName 商家名称
     * @apiParam {String} keyword 产品编号/名称
     * @apiParam {String=SERVICE("服务"), GOODS("商品"), ALL("全部")} type <code>必须参数</code> 产品类型 默认 ALL
     * @apiParam {String} sortByName 排序字段 quantity("库存"),sort_num("排序")
     * @apiParam {String} sort 排序类型 ASC("升序"), DESC("降序")
     * @apiParam {Integer} pageNo 页码
     * @apiParam {Integer} pageSize
     *
     * @apiSuccess {Long} id 产品ID
     * @apiSuccess {Date} dateCreated 创建时间
     * @apiSuccess {String} type 产品类型
     * @apiSuccess {String} name 产品名称
     * @apiSuccess {BigDecimal} basePrice 原价
     * @apiSuccess {BigDecimal} sellPrice 出售价
     * @apiSuccess {Long} quantity 库存量
     * @apiSuccess {String} barcode 产品编号
     * @apiSuccess {String} logoUrl LOGO图
     * @apiSuccess {String} note 卖点介绍
     * @apiSuccess {String=SELLING("在售"), SOLDOUT("已下架"), EXPIRED("已过期"), DELETED("已删除"), WAIT_APPLY("待申请"), WAIT_AUDIT("待审核"), AUDIT_PASS("审核通过"), AUDIT_FAIL("审核不通过")} status 产品状态
     * @apiSuccess {Long} mallId 平台ID
     * @apiSuccess {Long} merchantId 商家ID
     * @apiSuccess {String} viewCount 访问数
     * @apiSuccess {Long} customerCount 访客数
     * @apiSuccess {Long} saleCount 售出数
     * @apiSuccess {Long} verifyCount 核销数
     * @apiSuccess {Long} sortByNum 排序
     * @apiSuccess {String} merchantName 商家名称
     * @apiSuccess {String} shippingType 支持的物流类型 SHOP_PICKUP("到店自取"), SHIPPING("物流"), SHOP_PICKUP_AND_SHIPPING("物流及到店自取")
     *
     * @apiSuccessExample {json} Success-Response:
     * {
     * "code": "1",
     * "desc": "成功",
     * "data": {
     * "data": [
     *      {
     *          "id": 71,
     *          "dateCreated": "2016-06-01 14:13:43",
     *          "type": "GOODS",
     *          "name": "宇宙",
     *          "basePrice": 110,
     *          "sellPrice": 100,
     *          "quantity": 998,
     *          "logoUrl": "/20160601/201606011413084VOvLKgN.jpg",
     *          "status": "SELLING",
     *          "mallId": 1,
     *          "merchantId": 1,
     *          "viewCount": "35",
     *          "customerCount":10,
     *          "saleCount": 2,
     *          "verifyCount": 2,
     *          "shippingType":"SHOP_PICKUP_AND_SHIPPING",
     *          "merchantName": "宇宙"
     *       }
     *    ],
     *    "totalCount": 10,
     *    "totalPage": 1,
     *    "pageNo": 0,
     *    "pageSize": 1
     *   }
     * }
     */
    @RequestMapping(value = Routes.MALL_EXPLOSION_PRODUCT_LIST, method = RequestMethod.GET)
    public JsonResult list(HttpServletRequest request, ProductDto productDto) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (userInfoDto.mall == null || userInfoDto.mall.getId() == null) {
                jsonResult.remind("平台id 不能为空", log);
            }
            if (StringUtils.isNotEmpty(productDto.getType()) && !EnumUtils.isValidEnum(ProductType.class, productDto.getType())) {
                jsonResult.remind("产品类型只允许 SERVICE(\"服务\"), GOODS(\"商品\"), ALL(\"全部\")", log);
                return;
            }
            PageResult<ProductDto> pageResult = productSrv.findExplosionProducts(userInfoDto.mall.getId(), productDto.getType(),ProductClientType.EXPLOSION, productDto.getMerchantName(), productDto.getKeyword(), this.getPage(productDto.getPageNo(), productDto.getPageSize()),productDto.getSortByName(),productDto.getSort());
            pageResult.data.stream().map(product -> {
                Long saleCount = 0L;
                Long verifyCount = 0L;
                MerchantOrderItem caculateSaleCountAndVerifyCount =merchantOrderItemRepository.caculateSaleCountAndVerifyCountByMallIdAndMerchantIdAndProductId(product.getMallId(),product.getMerchantId(),product.getId());
                if (null!=caculateSaleCountAndVerifyCount){
                    saleCount = caculateSaleCountAndVerifyCount.getBuyCount();
                    verifyCount = caculateSaleCountAndVerifyCount.getVerifyCount();
                }
                product.setSaleCount(saleCount);
                product.setVerifyCount(verifyCount);
                product.setViewCount("0");
                product.setCustomerCount(0L);
                List<ProductEvent> productEventList = productEventRepository.findProductStatisticByproductId(product.getId());
                productEventList.stream().filter(productEvent -> ProductEventType.CLICKED == productEvent.getEventType()).forEach(productEvent -> {
                    product.setCustomerCount(productEvent.getNum());
                });
                List<ProductEvent> productEventCountList = productEventRepository.findProductStatisticViewCountByproductId(product.getId(),product.getMallId(),product.getMerchantId());
                productEventCountList.stream().filter(productEvent -> ProductEventType.CLICKED == productEvent.getEventType()).forEach(productEvent -> {
                    product.setViewCount(String.valueOf(productEvent.getNum()));
                });
                return product;
            }).collect(Collectors.toList());
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {put} /v1/mall/explosion/product/del 删除精选产品
     * @apiGroup MALL_PRODUCT
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {List} ids <code>必要参数</code> 产品ID集合
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *      "success": "Y"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_EXPLOSION_PRODUCT_DEL, method = RequestMethod.PUT)
    public JsonResult del(@RequestBody ProductDto productDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (userInfoDto.mall == null || userInfoDto.mall.getId() == null) {
                jsonResult.remind("平台id 不能为空", log);
                return;
            }
            List<Long> ids = productDto.getIds();
            if (ids == null || ids.size()==0) {
                jsonResult.remind("产品id 不能为空", log);
                return;
            }
            List<Product> products = merchantProductRepository.findByIdInAndMallId(ids,userInfoDto.mall.getId());
            if(products==null) {
                jsonResult.remind("产品id 不存在", log);
                return;
            }
            if(ids.size()!=products.size()) {
                jsonResult.remind("产品数据有些已不存在", log);
                return;
            }
            productSrv.delExplosionProduct(userInfoDto.mall.getId(),ids);
            String ret = "{\"success\":\"Y\"}";
            jsonResult.data = JSONObject.fromObject(ret);
        };
        return doing.go(request, log);
    }

    /**
     * @api {post} /v1/mall/explosion/product/update 精选产品更新排序
     * @apiGroup MALL_PRODUCT
     * @apiVersion 1.0.0
     *
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain 请求域名
     * @apiHeader {String} platformMark    平台类型
     *
     * @apiParam {Long} productId <code>必要参数</code> 产品ID
     * @apiParam {Long} sortByNum <code>必要参数</code> 排序号
     *
     * @apiSuccessExample {json} Success-Response:
     *
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": {
     *      "success": "Y"
     *   }
     * }
     *
     */
    @RequestMapping(value = Routes.MALL_EXPLOSION_PRODUCT_UPDATE, method = RequestMethod.POST)
    public JsonResult update(@RequestBody ProductDto productDto, HttpServletRequest request) {
        UserInfoDto userInfoDto = userHelper.getSession(request);
        RestDoing doing = jsonResult -> {
            if (userInfoDto.mall == null || userInfoDto.mall.getId() == null) {
                jsonResult.remind("平台id 不能为空", log);
                return;
            }
            Long productId = productDto.getProductId();
            if (productId == null) {
                jsonResult.remind("产品id 不能为空", log);
                return;
            }
            Product product = merchantProductRepository.findByIdAndMallId(productId,userInfoDto.mall.getId());
            if(product==null) {
                jsonResult.remind("产品id 不存在", log);
                return;
            }
            product.setSortNum(productDto.getSortByNum());
            merchantProductRepository.save(product);
            String ret = "{\"success\":\"Y\"}";
            jsonResult.data = JSONObject.fromObject(ret);
        };
        return doing.go(request, log);
    }
}
